/*********************************************************************************
 *      Copyright:  (C) 2025 LingYun<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  thread.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(12/03/25)
 *         Author:  LingYun <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "12/03/25 17:36:17"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

void *thread_worker1(void *args);
void *thread_worker2(void *args);

int main(int argc, char **argv)
{
	int					shared_var = 1000;
	pthread_t			tid;
	pthread_attr_t		thread_attr;

	if(pthread_attr_init(&thread_attr))       //初始化init
	{
		printf("pthread_attr_init() failure: %s\n", strerror(errno));
		return -1;
	}

	if(pthread_attr_setstacksize(&thread_attr, 120*1024))       //设置栈的大小
	{
		printf("pthread_attr_setstacksize() failure: %s\n", strerror(errno));
		return -1;
	}

	if(pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED))       //设置栈属性为分离
	{
		printf("pthread_attr_setdetachstate() failure: %s\n", strerror(errno));
		return -1;
	}

	pthread_create(&tid, &thread_attr, thread_worker1, &shared_var);           //创建了一个线程，为分离态
	printf("Thread worker1 tid[%ld] created ok\n", tid);

	pthread_create(&tid, NULL, thread_worker2, &shared_var);               //创建线程2，为会和态（默认NULL）
	printf("Thread worker2 tid[%ld] created ok\n", tid);
	
	pthread_attr_destroy(&thread_attr);         //初始化完后摧毁

	//等待直到thread worker2 exit
	pthread_join(tid, NULL);

	while(1)
	{
		printf("Main/Control thread shared_var: %d\n", shared_var);
		sleep(10);
	}
}

void *thread_worker1(void *args)        //线程启动时调用的函数
{
	int 		*ptr = (int *)args; 

	if(!args)                        //如果没有传参数
	{
		printf("%s() get invalid arguments\n", __FUNCTION__);
		pthread_exit(NULL);          //线程退出，不能调exit()，否则整个进程退出
	}

	printf("Thread worker1 [%ld] start running...\n", pthread_self());         //线程开始工作，pthread_self()线程号

	while(1)                  //子线程工作
	{
		printf("+++: %s before shared_var++: %d\n", __FUNCTION__, *ptr);
		*ptr += 1;            //临界区域，多个线程共同访问的区域
		sleep(2);
		printf("+++: %s after sleep shared_var: %d\n", __FUNCTION__, *ptr);    //打印值应为1001
	}

	printf("Thread worker1 exit...\n");

	return NULL;
}

void *thread_worker2(void *args)
{
	int				*ptr = (int *)args;

	if(!args)
	{
		printf("%s() get invalid arguments\n", __FUNCTION__);
		pthread_exit(NULL);
	}
	printf("Thread worker2 [%ld] start running...\n ", pthread_self());

	while(1)                  //第2个子线程开始工作
	{
		printf("---: %s before shared_var++: %d\n", __FUNCTION__, *ptr);
		*ptr += 1;
		sleep(2);
		printf("---: %s after sleep shared_var: %d\n", __FUNCTION__, *ptr);
	}

	printf("Thread worker2 exit...\n");

	return NULL;
}


